// Copyright (c) MatrixFramework. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Matrix.ServiceCommunication.Options;

namespace Matrix.ServiceCommunication.Discovery.LoadBalancing;

/// <summary>
/// 负载均衡器工厂
/// </summary>
public class LoadBalancerFactory
{
    private readonly ILogger<LoadBalancerFactory> _logger;
    private readonly IOptionsMonitor<EnhancedDiscoveryOptions> _options;
    private readonly ILoadBalancer _defaultLoadBalancer;

    public LoadBalancerFactory(
        ILogger<LoadBalancerFactory> logger,
        IOptionsMonitor<EnhancedDiscoveryOptions> options)
    {
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        _options = options ?? throw new ArgumentNullException(nameof(options));
        _defaultLoadBalancer = CreateLoadBalancer(options.CurrentValue.LoadBalancingStrategy);
    }

    /// <summary>
    /// 创建负载均衡器
    /// </summary>
    /// <param name="strategy">负载均衡策略</param>
    /// <returns>负载均衡器实例</returns>
    public ILoadBalancer CreateLoadBalancer(LoadBalancingStrategy strategy)
    {
        var loadBalancer = strategy switch
        {
            LoadBalancingStrategy.RoundRobin => new RoundRobinLoadBalancer(),
            LoadBalancingStrategy.Random => new RandomLoadBalancer(),
            LoadBalancingStrategy.WeightedRoundRobin => new WeightedRoundRobinLoadBalancer(),
            LoadBalancingStrategy.LeastConnections => new LeastConnectionsLoadBalancer(),
            _ => new RoundRobinLoadBalancer()
        };

        _logger.LogDebug("创建负载均衡器: {Strategy} -> {LoadBalancerType}",
            strategy, loadBalancer.GetType().Name);

        return loadBalancer;
    }

    /// <summary>
    /// 获取当前配置的负载均衡器
    /// </summary>
    /// <returns>负载均衡器实例</returns>
    public ILoadBalancer GetCurrentLoadBalancer()
    {
        var currentStrategy = _options.CurrentValue.LoadBalancingStrategy;
        return CreateLoadBalancer(currentStrategy);
    }

    /// <summary>
    /// 获取默认负载均衡器
    /// </summary>
    /// <returns>默认负载均衡器实例</returns>
    public ILoadBalancer GetDefaultLoadBalancer()
    {
        return _defaultLoadBalancer;
    }
}